# coding=utf-8
"""
注册中心
"""
import os

from flask import Blueprint, request

from server.base.beanret import BeanRet
from server.base.cachedata import CacheData
from server.base.log4py import logger

sv = Blueprint('login', __name__)


@sv.route('/reg/<clientId>.shtml', methods=['GET'])
def login(clientId=None):
    '''
    客户端注册到服务器接口
    '''
    try:
        logger.info('客户端clientId:' + str(clientId))
        ip = request.remote_addr
        CacheData().reg(clientId, ip)
        return BeanRet(success=True, info="注册成功").toJson()
    except:
        return BeanRet(success=False, info="注册失败", code=9999).toJson()


@sv.route('/state.shtml', methods=['GET'])
def checkState():
    '''
    检测状态
    :return:
    '''
    try:
        logger.info('服务器检测客户端状态')
        cacheData = CacheData()
        clients = cacheData.listClients()
        for client in clients:
            try:
                ip = client["ip"]
                # 实现pingIP地址的功能，-c1指发送报文一次，-w1指等待1秒
                exit_code = os.system('ping -c1 -w1 ' + ip)
                logger.info("ping 的状态码：" + str(exit_code))
                if exit_code == 0:
                    CacheData().checkState(str(client["id"]), "Online")
                else:
                    CacheData().checkState(str(client["id"]), "Offline")
            except:
                CacheData().checkState(str(client["id"]), "Offline")
                logger.error("网络ping不通")

        return BeanRet(success=True, info="注册成功", data=cacheData.listClients()).toJson()
    except:
        return BeanRet(success=False, info="注册失败", code=9999).toJson()
